const app = getApp();
const api = require('../../utils/api');
const md5 = require('../../utils/md5');
import QRCode from '../../utils/weapp-qrcode'; //引入生成二维码的插件

Page({
    data: {
        id: '',
        orderType: 0, //订单类型 0 普通订单(商城订单) 1 购券订单
        payType: '', //支付类型 miniapp-wx 微信 miniapp-ccb 建行
        isPurchaseAgent: false, //是否代购
        isStaff: false, //是否店员处理订单
        orderDetail: '',
        couponSyncBuy: 0, //同步购券金额

        isSetPayPassword: true, //是否设置过支付密码
        showPassword: false, 
        isSetPayPassword: true, //是否已经设置支付密码

        showPayQrcode: false, //付款码弹窗
        payQrcodeUrl: '',
    },
    onLoad(options) {
        if(options.id) {
            this.setData({
                id: options.id
            });
        }
        if(options.type) {
            this.setData({
                orderType: options.type
            });
        }
        if(options.dir) {
            this.setData({
                isStaff: true
            });
        }
    },
    onShow() {
        this.setData({
            isSetPayPassword: app.globalData.userInfo.isSetPayPassword == 1 ? true : false
        });
        
        if(this.data.orderType == 1) {
            this.getCouponOrderDetail();
        } else {
            this.getOrderDetail();
        }
    },

    getOrderDetail() { //获取商城订单详情
        api.post(`/order/detail?orderId=${this.data.id}`)
            .then(res => {
                //处理数据
                let data = res;
                data.payableAmountShow = res.payableAmount.toFixed(2);
                data.createTime = app.filterDate(res.createTime);
                //计算购券金额
                let couponSyncBuy = 0;
                res.skuList.forEach(item => {
                    if(item.productType == 1) {
                        couponSyncBuy = couponSyncBuy + item.couponDenomination * item.quantity;
                    }
                });

                this.setData({
                    orderDetail: data,
                    couponSyncBuy: couponSyncBuy,
                    isPurchaseAgent: res.orderType == 1 ? true : false
                });
            })
    },
    getCouponOrderDetail() { //获取购券订单详情
        api.post('/coupon/order/detail?orderId=' + this.data.id)
            .then(res => {
                //处理数据
                let data = res;
                data.payableAmountShow = res.payAmount.toFixed(2);
                data.createTime = app.filterDate(res.createTime);

                this.setData({
                    orderDetail: data
                });
            })
    },

    checkPayType() { //检查当前支持的支付方式
        api.post('/payment/payType')
            .then(res => {
                this.setData({
                    payType: res
                });
                this.submitPay();
            })
    },
    submitPay() { //提交支付
        if(this.data.orderType == 1) { //**购券订单
            this.couponOrderPayByWeixin();
        } else if(this.data.orderDetail.isAccountPay) { //**普通(商城)订单，用账户余额支付
            setTimeout(() => {
                this.payStoreOrderByAccount();
            }, 600);
        } else if(this.data.orderDetail.isMemberPay) { //**普通(商城)订单，用券支付
            if(this.data.isPurchaseAgent && this.data.isStaff) {
                //代购订单，不需要输支付密码
                wx.showLoading({
                    title: '提交中，请稍后...',
                });
                setTimeout(() => {
                    this.payStoreOrder();
                }, 800);
            } else if(!this.data.isSetPayPassword) {
                //如果没有设置支付密码，提醒去设置
                wx.showModal({
                    title: '温馨提示',
                    content: `您还未设置支付密码！`,
                    confirmText: '去设置',
                    cancelText: '晚点设置',
                    success: res => {
                        if(res.confirm) {
                            wx.navigateTo({
                                url: '/pages/setPayPassword/setPayPassword',
                            })
                        } else {
                            this.cancelPay();
                        }
                    }
                });
            } else {
                //已设置支付密码
                if(this.data.orderDetail.isPaid == 1) {
                    //已完成券支付
                    wx.showLoading({
                        title: '提交中，请稍后...',
                    });
                    setTimeout(() => {
                        this.payStoreOrder();
                    }, 800);
                } else {
                    //未完成券支付，打开密码弹窗
                    this.openPassword();
                }
            }
        } else { //**普通(商城)订单，现金支付
            wx.showLoading({
                title: '提交中，请稍后...',
            });
            setTimeout(() => {
                this.payStoreOrder();
            }, 800);
        }
    },
    cancelPay() { //稍后再付
        wx.switchTab({
            url: '/pages/user/user',
        });
    },

    //****普通(商城)订单
    payStoreOrder() { //全现金支付
        if(this.data.payType == 'miniapp-wx') { //微信支付
            api.post('/payment/weixin/order/pay', {
                orderId: this.data.id,
                payableAmount: this.data.orderDetail.payableAmount, //应付金额
                couponAmount: this.data.orderDetail.couponAmountPay, //应付券数量
            })
                .then(res => {
                    wx.hideLoading();
                    this.weixinPay(res); //调用微信支付
                })
        } else if(this.data.payType == 'miniapp-ccb') { //建行支付
            api.post('/payment/ccb/pay', {
                orderId: this.data.id,
                payableAmount: this.data.orderDetail.payableAmount, //应付金额
                couponAmount: this.data.isPurchaseAgent && this.data.isStaff && this.data.orderDetail.isMemberPay ? this.data.orderDetail.couponAmount : this.data.orderDetail.couponAmountPay, //应付券数量
                payMethod: this.data.isPurchaseAgent && this.data.isStaff ? 'QR_CODE' : '',
                q: this.data.isPurchaseAgent && this.data.isStaff ? -1 : 0,
            })
                .then(res => {
                    if(this.data.isPurchaseAgent && this.data.isStaff) {
                        //代购收银订单，生成付款二维码
                        this.setData({
                            showPayQrcode: true,
                        });
                        this.createPayQrcode(decodeURIComponent(res));
                    } else {
                        //普通自提订单，调起微信支付
                        let data = JSON.parse(res);
                        this.ccbPay(data);
                    }
                    wx.hideLoading();
                })
                .catch(() => {
                    wx.hideLoading();
                })
        }
    },
    payStoreOrderByAccount() { //账户余额支付
        wx.showModal({
            title: '温馨提示',
            content: `系统将从您的账户余额中扣除【${this.data.orderDetail.payableAmount}元】，您是否确认支付该笔订单？`,
            confirmText: '确认支付',
            cancelText: '稍后再付',
            success: res => {
                if(res.confirm) {
                    api.post('/payment/account/pay', {
                        orderNo: this.data.orderDetail.orderNo,
                        payableAmount: this.data.orderDetail.payableAmount, //应付金额
                        a: (new Date()).getTime(),
                        q: -1,
                    })
                        .then(() => {
                            wx.showToast({
                                title: '支付成功！',
                                icon: 'success'
                            });
                            setTimeout(() => {
                                wx.switchTab({
                                    url: '/pages/user/user',
                                });
                            }, 1000);
                        })
                } else if(res.cancel) {
                    setTimeout(() => {
                        wx.switchTab({
                            url: '/pages/user/user',
                        });
                    }, 400);
                }
            }
        })
    },
    //****自提订单，调起微信支付
    weixinPay(res) { //调起微信支付
        wx.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.packageValue,
            signType: res.signType,
            paySign: res.paySign,
            success: () => {
                this.checkWeixinPayResult();
            },
            fail: () => {
                wx.showToast({
                    title: '支付失败，请重试！',
                    icon: 'none'
                });
            }
        })
    },
    ccbPay(res) { //调起建行支付
        wx.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
            success: () => {
                this.checkWeixinPayResult();
            },
            fail: () => {
                wx.showToast({
                    title: '支付失败，请重试！',
                    icon: 'none'
                });
            }
        })
    },
    checkWeixinPayResult() { //检查微信支付结果
        let url = '';
        if(this.data.payType == 'miniapp-wx') {
            url = '/payment/weixin/order/query'
        } else if(this.data.payType == 'miniapp-ccb') {
            url = '/payment/ccb/order/query'
        }
        api.post(`${url}?orderNo=${this.data.orderDetail.orderNo}`)
            .then(res => {
                let status = res;
                switch(status) {
                    case 'SUCCESS':
                        wx.showToast({
                            title: '支付成功！',
                            icon: 'success'
                        });
                        setTimeout(() => {
                            wx.switchTab({
                                url: '/pages/user/user',
                            })
                        }, 1000);
                        break;
                    case 'FAIL':
                        wx.showToast({
                            title: '支付失败，请重试！',
                            icon: 'none'
                        });
                        break;
                    case 'CANCEL':
                        wx.showToast({
                            title: '支付已取消！',
                            icon: 'none'
                        });
                        break;
                    case 'WAIT_PAY':
                        setTimeout(() => {
                            this.checkWeixinPayResult();
                        }, 500);
                        break;
                }
            })
    },

    //****收银订单，使用付款二维码支付
    createPayQrcode(url) { //生成付款二维码
        new QRCode('myQrcode', {
            text: url,
            width: this.createRpx2px(500),
            height: this.createRpx2px(500),
            padding: 12, // 生成二维码四周自动留边宽度，不传入默认为0
            correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
            callback: res => {
                this.setData({
                    payQrcodeUrl: res.path
                });
            }
        });
    },
    createRpx2px(rpx) {
        return wx.getWindowInfo().windowWidth / 750 * rpx
    },
    checkPayByQrcodeResult() { //检查扫码支付结果
        api.post(`/order/detail?orderId=${this.data.id}`)
            .then(res => {
                if(res.isPaid == 0 || res.isPaid == 1) {
                    wx.showToast({
                        title: '支付未完成，请稍后再试！',
                        icon: 'none'
                    });
                } else {
                    wx.showToast({
                        title: '支付成功！',
                        icon: 'success'
                    });
                    this.setData({
                        showPayQrcode: false,
                    });
                    setTimeout(() => {
                        wx.switchTab({
                            url: '/pages/user/user',
                        })
                    }, 1000);
                }
            })
    },
    closePayQrcode() {
        this.setData({
            showPayQrcode: false,
        });
    },
    
    //****普通(商城)订单：使用购物券支付
    openPassword() { //打开支付密码弹窗
        this.setData({
            showPassword: true,
        });
    },
    closePassword() { //关闭支付密码弹窗
        this.setData({
            payPassword: '',
            showPassword: false,
        });
    },
    bindinput(e) { //输入框监听
        let item = e.currentTarget.dataset.item;
        let val = e.detail.value;
        this.setData({
            [item]: val
        });
    },
    submitPassword() { //提交购物券支付密码
        if(!this.data.payPassword) {
            wx.showToast({
                title: `请输入支付密码`,
                icon: 'none'
            });
            return;
        }
        
        let password = this.data.payPassword;
        if(this.data.payType == 'miniapp-wx') { //微信支付
            api.post('/payment/weixin/order/pay', {
                orderId: this.data.id,
                payableAmount: this.data.orderDetail.payableAmount, //应付金额
                couponAmount: this.data.orderDetail.couponAmount, //用券金额
                abc: md5.md5(password)
            })
                .then(res => {
                    if(this.data.orderDetail.payableAmount == 0) { //应付金额为0时（只需支付购物券）
                        wx.showToast({
                            title: '支付成功',
                            icon: 'success'
                        });
        
                        this. closePassword();
                        setTimeout(() => {
                            wx.switchTab({
                                url: '/pages/user/user',
                            })
                        }, 1000);
                    } else { //应付金额>0时，需发起微信支付
                        this.closePassword();
                        this.weixinPay(res); //调用微信支付
                    }
                })
        } else if(this.data.payType == 'miniapp-ccb') { //建行支付
            api.post('/payment/ccb/pay', {
                orderId: this.data.id,
                payableAmount: this.data.orderDetail.payableAmount, //应付金额
                couponAmount: this.data.orderDetail.couponAmount, //应付券数量
                abc: md5.md5(password)
            })
                .then(res => {
                    if(this.data.orderDetail.payableAmount == 0) { //应付金额为0时（只需支付购物券）
                        wx.showToast({
                            title: '支付成功',
                            icon: 'success'
                        });
        
                        this. closePassword();
                        setTimeout(() => {
                            wx.switchTab({
                                url: '/pages/user/user',
                            })
                        }, 1000);
                    } else { //应付金额>0时，需发起微信支付
                        this.closePassword();
                        
                        let data = JSON.parse(res);
                        this.ccbPay(data);
                    }
                })
        }
    },

    gotoSetPassword() { //去设置支付密码
        wx.navigateTo({
            url: '/pages/setPayPassword/setPayPassword',
        });
    },

    //****购券订单
    couponOrderPayByWeixin() { //购券订单支付
        let params = {
            orderId: this.data.id,
            payableAmount: this.data.orderDetail.payAmount,
        }
        api.post('/payment/weixin/coupon/pay', params)
            .then(res => {
                //调用微信支付
                wx.requestPayment({
                    timeStamp: res.timeStamp,
                    nonceStr: res.nonceStr,
                    package: res.packageValue,
                    signType: res.signType,
                    paySign: res.paySign,
                    success: () => {
                        this.checkWeixinPayResult();
                    },
                    fail: () => {
                        wx.showToast({
                            title: '支付失败，请重试！',
                            icon: 'none'
                        });
                    }
                })
            })
    },
})